from django.db import models


class MatchmakingQueue(models.Model):
    """匹配队列"""
    user = models.ForeignKey('accounts.User', on_delete=models.CASCADE, verbose_name="用户")
    deck = models.ForeignKey('decks.Deck', on_delete=models.CASCADE, verbose_name="卡组")
    joined_at = models.DateTimeField(auto_now_add=True, verbose_name="加入时间")
    is_active = models.BooleanField(default=True, verbose_name="是否活跃")
    matchmaking_rating = models.IntegerField(default=0, verbose_name="匹配评分")
    max_wait_time = models.IntegerField(default=300, verbose_name="最大等待时间（秒）")
    search_range = models.IntegerField(default=200, verbose_name="搜索范围")
    
    class Meta:
        verbose_name = "匹配队列"
        verbose_name_plural = "匹配队列"
        ordering = ['joined_at']
        constraints = [
            models.UniqueConstraint(
                fields=['user'],
                condition=models.Q(is_active=True),
                name='unique_active_user_queue'
            )
        ]
    
    def __str__(self):
        return f"{self.user.nickname} - {self.deck.name}"
    
    def save(self, *args, **kwargs):
        # 自动计算匹配评分
        if not self.matchmaking_rating:
            self.matchmaking_rating = self.user.matchmaking_rating
        super().save(*args, **kwargs)
    
    @property
    def wait_time(self):
        """等待时间（秒）"""
        from django.utils import timezone
        return int((timezone.now() - self.joined_at).total_seconds())
    
    @property
    def is_timeout(self):
        """是否超时"""
        return self.wait_time > self.max_wait_time
